<script setup lang="ts">
import { sendCodeApi } from "@/apis/user";
import { ElMessage } from "element-plus";
import { ref, defineProps } from "vue";

const isSend = ref(false);
const props = defineProps(["phoneNumber"]);
const sendTime = ref(60);
const sentCode = async () => {
  if (isSend.value)
    return ElMessage({
      message: "请稍后再试",
      type: "warning",
      offset: 20,
      duration: 2000,
      customClass: "topMessage",
    });
  const res = await sendCodeApi({ phone: props.phoneNumber });
  if (res.data.code !== 200) {
    ElMessage({
      message: "发送失败",
      type: "error",
      offset: 20,
      duration: 2000,
      customClass: "topMessage",
    });
    return;
  }
  isSend.value = true;
  let timer = setInterval(() => {
    sendTime.value--;
    if (sendTime.value <= 0) {
      isSend.value = false;
      sendTime.value = 60;
      clearInterval(timer);
    }
  }, 1000);
};
</script>
<template>
  <button class="sendCodeBtn" @click="sentCode" type="button">
    {{ isSend ? `${sendTime}后再试` : "发送验证码" }}
  </button>
</template>
<style scoped lang="scss">
.sendCodeBtn {
  margin-left: 5px;
  height: 32px;
  border: 0;
  border-radius: 10px;
  font-size: 12px;
  width: 80px;
  background-color: rgba($color: rgb(250, 10, 10), $alpha: 0.4);
  color: white;
}
</style>
